package com.jb.workflow.app.ui;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import com.jb.workflow.app.bean.TodoTask;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import net.oschina.app.AppConfig;
import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.Result;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.ui.BaseActivity;
import net.oschina.app.ui.LoginDialog;

public class TodoDetail extends BaseActivity {
	
	public final static String TAG = "TodoDetail";
	
	private FrameLayout mHeader;
	private LinearLayout mFooter;
	private ImageView mBack;
	private ImageView mRefresh;
	private TextView mHeadTitle;
	private ProgressBar mProgressbar;
	private ScrollView mScrollView;
	
	private TextView mTitle;
	private TextView mAuthor;
	private TextView mPubDate;
	private TextView mCommentCount;
	
	private WebView mWebView;
    private Handler mHandler;
    
    private int todoId;
    private String todoCustomer;
    private String todoComment;
    private String todoOrderId;
    private String todoDate;
    private boolean todoNeedDriver;
    private String todoStep;
    private String todoAuthor;
    //claim or 
    private String action;
    
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	private final static int DATA_LOAD_FAIL = 0x003;
	
    //private int curId;
    private String _content;
    //private String _account;
    
    private EditText mFootEditer;
	private Button mFootComplete;	
	private ProgressDialog mProgress;
	private InputMethodManager imm;
	private String tempTodoNoticeKey = AppConfig.TEMP_COMMENT;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.todo_detail);
        
        this.initView();        
        this.initData();
    }
    
    //****增加其他类型任务的显示支持，可能不是客户，订单号等流程变量
    // 隐藏输入发表回帖状态
    private void hideEditor(View v) {
    	imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
    
    //初始化视图控件
    private void initView()
    {
    	todoId = getIntent().getIntExtra("todoId", 0);
    	if (todoId <= 0) return;
    	
    	todoCustomer = getIntent().getStringExtra("todoCustomer");
    	todoComment = getIntent().getStringExtra("todoComment");
    	todoOrderId = getIntent().getStringExtra("todoOrderId");
    	todoNeedDriver = getIntent().getBooleanExtra("todoNeedDriver", true);
    	todoDate = getIntent().getStringExtra("todoDate");
    	todoAuthor = getIntent().getStringExtra("todoAuthor");
    	
    	if(todoId > 0) tempTodoNoticeKey = AppConfig.TEMP_TODO_NOTICE + "_" + 1 + "_" + todoId;
    	
    	mHeader = (FrameLayout)findViewById(R.id.todo_detail_header);
    	mFooter = (LinearLayout)findViewById(R.id.todo_detail_footer);
    	mBack = (ImageView)findViewById(R.id.todo_detail_back);
    	mRefresh = (ImageView)findViewById(R.id.todo_detail_refresh);
    	mProgressbar = (ProgressBar)findViewById(R.id.todo_detail_head_progress);
    	mHeadTitle = (TextView)findViewById(R.id.todo_detail_head_title);
    	//mViewSwitcher = (ViewSwitcher)findViewById(R.id.todo_detail_viewswitcher);
    	mScrollView = (ScrollView)findViewById(R.id.todo_detail_scrollview);
    	
    	//mDetail = (ImageView)findViewById(R.id.todo_detail_footbar_detail);
    	//mCommentList = (ImageView)findViewById(R.id.todo_detail_footbar_commentlist);
    	//mShare = (ImageView)findViewById(R.id.todo_detail_footbar_share);
    	//mFavorite = (ImageView)findViewById(R.id.todo_detail_footbar_favorite);
    	
    	//mDocTYpe = (ImageView)findViewById(R.id.todo_detail_documentType);
    	mTitle = (TextView)findViewById(R.id.todo_detail_title);
    	mAuthor = (TextView)findViewById(R.id.todo_detail_author);
    	mPubDate = (TextView)findViewById(R.id.todo_detail_date);
    	mCommentCount = (TextView)findViewById(R.id.todo_detail_commentcount);
    	
    	//mDetail.setEnabled(false);
    	
    	mWebView = (WebView)findViewById(R.id.todo_detail_webview);
    	mWebView.getSettings().setSupportZoom(true);
    	mWebView.getSettings().setBuiltInZoomControls(true);
    	mWebView.getSettings().setDefaultFontSize(15);
    	//UIHelper.addWebImageShow(this, mWebView);
    	
    	mBack.setOnClickListener(UIHelper.finish(this));
    	//mFavorite.setOnClickListener(favoriteClickListener);
    	mRefresh.setOnClickListener(refreshClickListener);
    	//mAuthor.setOnClickListener(authorClickListener);
    	//mShare.setOnClickListener(shareClickListener);
    	//mDetail.setOnClickListener(detailClickListener);
    	//mCommentList.setOnClickListener(commentlistClickListener);
    	
//    	bv_comment = new BadgeView(this, mCommentList);
//    	bv_comment.setBackgroundResource(R.drawable.widget_count_bg2);
//    	bv_comment.setIncludeFontPadding(false);
//    	bv_comment.setGravity(Gravity.CENTER);
//    	bv_comment.setTextSize(8f);
//    	bv_comment.setTextColor(Color.WHITE);
    	
    	imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	
    	//mFootViewSwitcher = (ViewSwitcher)findViewById(R.id.todo_detail_foot_viewswitcher);
    	mFootComplete = (Button)findViewById(R.id.todo_detail_foot_complete);
    	mFootComplete.setOnClickListener(submitClickListener);
//    	mFootEditebox = (ImageView)findViewById(R.id.todo_detail_footbar_editebox);
//    	mFootEditebox.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View v) {
//				mFootViewSwitcher.showNext();
//				mFootEditer.setVisibility(View.VISIBLE);
//				mFootEditer.requestFocus();
//				mFootEditer.requestFocusFromTouch();
//			}
//		});
    	mFootEditer = (EditText)findViewById(R.id.todo_detail_foot_editer);
    	mFootEditer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){  
					imm.showSoftInput(v, 0);  
		        }  
		        else {  
		            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		            hideEditor(v);
		        }  
			}
		}); 
    	mFootEditer.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					hideEditor(v);
					return true;
				}
				return false;
			}
		});
    	// 编辑器添加文本监听
    	mFootEditer.addTextChangedListener(UIHelper.getTextWatcher(this, tempTodoNoticeKey));
    	
    	// 显示临时编辑内容
    	UIHelper.showTempEditContent(this, mFootEditer, tempTodoNoticeKey);
    	
    	int catalog = getIntent().getIntExtra("catalog", 0);
    	if (catalog == TodoTask.CATALOG_CLAIM) {//待签收
    		todoStep = "待签收";
    		action = Result.ACTION_CLAIM_WF;
    		mFootEditer.setEnabled(false);
    		//mFootEditer.setFocusable(false);
    		mFootComplete.setText("签收");
    	} else if (catalog == TodoTask.CATALOG_TODO) {//待完成
    		todoStep = "待完成(" + todoAuthor + ")";
    		action = Result.ACTION_COMPLETE_WF;
    		mFootEditer.setEnabled(true);
    		//mFootEditer.setEnabled(true);
    		mFootComplete.setText("完成");
    	} else {
    		mFooter.setVisibility(View.GONE);
    		//mFootEditer.setVisibility(View.GONE);
    		//mFootComplete.setVisibility(View.GONE);
    	}
    }
    
    //初始化控件数据
	private void initData()
	{	
		mHandler = new Handler()
		{
			public void handleMessage(Message msg) 
			{				
				if(msg.what == 1)
				{					
					headButtonSwitch(DATA_LOAD_COMPLETE);
					
					mTitle.setText(todoCustomer);
					mAuthor.setText(todoOrderId);
					mPubDate.setText(StringUtils.friendly_timewf(todoDate));
					mCommentCount.setText(todoStep);
					
//					//是否收藏
//					if(blogDetail.getFavorite() == 1)
//						mFavorite.setImageResource(R.drawable.widget_bar_favorite2);
//					else
//						mFavorite.setImageResource(R.drawable.widget_bar_favorite);
					
//					//显示评论数
//					if(blogDetail.getCommentCount() > 0){
//						bv_comment.setText(blogDetail.getCommentCount()+"");
//						bv_comment.show();
//					}else{
//						bv_comment.setText("");
//						bv_comment.hide();
//					}
					
					//String body = UIHelper.WEB_STYLE + todoDetail.getComment();
					//String body = todoDetail.getComment();
					
					//Log.i(TAG, todoComment);
//					//读取用户设置：是否加载文章图片--默认有wifi下始终加载图片
//					boolean isLoadImage;
//					AppContext ac = (AppContext)getApplication();
//					if(AppContext.NETTYPE_WIFI == ac.getNetworkType()){
//						isLoadImage = true;
//					} else {
//						isLoadImage = ac.isLoadImage();
//					}
//					if(isLoadImage){
//						body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+","$1");
//						body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+","$1");
//						
//						// 添加点击图片放大支持
//						body = body.replaceAll("(<img[^>]+src=\")(\\S+)\"",
//								"$1$2\" onClick=\"javascript:mWebViewImageListener.onImageClick('$2')\"");
//					}else{
//						body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>","");
//					}
					
					mWebView.loadDataWithBaseURL(null, todoComment, "text/plain", "utf-8", null);
					//mWebView.setWebViewClient(UIHelper.getWebViewClient());
					
					//发送通知广播
					if(msg.obj != null) {
						UIHelper.sendBroadCast(TodoDetail.this, (Notice)msg.obj);
					}
				}
				else if(msg.what == 0)
				{
					headButtonSwitch(DATA_LOAD_FAIL);
					
					UIHelper.ToastMessage(TodoDetail.this, R.string.msg_load_is_null);
				}
				else if(msg.what == -1 && msg.obj != null)
				{
					headButtonSwitch(DATA_LOAD_FAIL);
					
					((AppException)msg.obj).makeToast(TodoDetail.this);
				}
			}
		};
		
		initData(todoId, false);
	}
	
    private void initData(final int todoId, final boolean isRefresh)
    {	
    	headButtonSwitch(DATA_LOAD_ING);
    	
		new Thread(){
			public void run() {
                Message msg = new Message();
				try {//****得到任务的详细信息
					//todoDetail = (TodoTask)((AppContext)getApplication()).getBlog(todoId, isRefresh);
					msg.what = 1;
					msg.obj = null;
	                //msg.what = (blogDetail!=null && blogDetail.getId()>0) ? 1 : 0;
	                //msg.obj = (blogDetail!=null) ? blogDetail.getNotice() : null;
	            } catch (Exception e) {
	                e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
                mHandler.sendMessage(msg);
			}
		}.start();
    }
    
    private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			hideEditor(v);
			initData(todoId, true);
			//loadLvCommentData(curId,0,mCommentHandler,UIHelper.LISTVIEW_ACTION_REFRESH);
		}
	};
    
	private View.OnClickListener submitClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {	
			//_id = curId;
			
//			if(curId == 0) {
//				return;
//			}
			
			_content = mFootEditer.getText().toString();
			//允许不输入备注
//			if(StringUtils.isEmpty(_content)) {
//				UIHelper.ToastMessage(v.getContext(), "请输入评论内容");
//				return;
//			}
			
			final AppContext ac = (AppContext)getApplication();
			if(!ac.isLogin()) {
				UIHelper.showLoginDialog(TodoDetail.this);
				return;
			}
				
			//_account = ac.getLoginAccount();
			
			mProgress = ProgressDialog.show(v.getContext(), null, "提交中···", true, true); 			
			
			final Handler handler = new Handler() {
				public void handleMessage(Message msg) {
					
					if(mProgress != null) mProgress.dismiss();
					
					if(msg.what == 1) {
						Result res = (Result)msg.obj;
						if(res.OK()) {
							UIHelper.ToastMessage(TodoDetail.this, res.getErrorMessage());
							//发送通知广播
							if(res.getNotice() != null) {
								UIHelper.sendBroadCast(TodoDetail.this, res.getNotice());
							}
							//恢复初始底部栏
							//mFootViewSwitcher.setDisplayedChild(0);
							mFootEditer.clearFocus();
							mFootEditer.setText("");
							//mFootEditer.setVisibility(View.GONE);
							//跳到评论列表
					    	//viewSwitch(VIEWSWITCH_TYPE_COMMENTS);
					    	//更新评论列表
					    	//lvCommentData.add(0,res.getComment());
					    	//lvCommentAdapter.notifyDataSetChanged();
					    	//mLvComment.setSelection(0);        	
							//显示评论数
					        //int count = blogDetail.getCommentCount() + 1;
					        //blogDetail.setCommentCount(count);
							//bv_comment.setText(count+"");
							//bv_comment.show();
							//清除之前保存的编辑内容
							ac.removeProperty(tempTodoNoticeKey);
							
							//返回Main页面，并且刷新
							//Intent intent = new Intent();
							//intent.putExtra("COMMENT_SERIALIZABLE", res.getComment());
							//setResult(RESULT_OK);
							//setResult(RESULT_OK, intent);
							//跳转到文章详情
							//finish();
						}
						else { //逻辑错误，退出页面并且刷新
							UIHelper.ToastMessage(TodoDetail.this, getString(R.string.wf_submit_fail) + msg.obj);
						}
						setResult(RESULT_OK);//成功或者逻辑错误，则退出并且刷新列表
						finish();
					} else if(msg.what == 0) { //其他错误，只提示不退出
						((AppException)msg.obj).makeToast(TodoDetail.this);
					}
					else { //网络等其他错误，不退出当前页面
						((AppException)msg.obj).makeToast(TodoDetail.this);
					}
				}
			};
			new Thread(){
				public void run() {
					Message msg = new Message();
					Result res = new Result();
					try {
						res = ac.operateTask(action, Integer.toString(todoId), makeJsonParams());
						msg.what = 1;
						msg.obj = res;
		            } catch (AppException e) {
		            	e.printStackTrace();
						msg.what = -1;
						msg.obj = e;
		            }
					handler.sendMessage(msg);
				}
			}.start();
			

		}
	};
	
	private String makeJsonParams() {
		String params = "[]";
		if (action == Result.ACTION_COMPLETE_WF && !StringUtils.isEmpty(_content)) {
			
			try {
				//拼接下评论
				String comment = todoComment + "\r\n\r\n-------" + todoAuthor + " " + StringUtils.getCurrentDT() + "-------\r\n" + _content;
				JSONArray paramsJArr = new JSONArray(); 
				
				JSONObject obj = new JSONObject();
				//obj.put("name", "comment");
				obj.put("id", "comment");
				obj.put("value", comment);
				paramsJArr.put(obj);
				
				params = paramsJArr.toString();
			} catch (JSONException e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}
		
		return params;
	}
    
    /**
     * 头部按钮展示
     * @param type
     */
    private void headButtonSwitch(int type) {
    	switch (type) {
		case DATA_LOAD_ING:
			mScrollView.setVisibility(View.GONE);
			mProgressbar.setVisibility(View.VISIBLE);
			mRefresh.setVisibility(View.GONE);
			break;
		case DATA_LOAD_COMPLETE:
			mScrollView.setVisibility(View.VISIBLE);
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		case DATA_LOAD_FAIL:
			mScrollView.setVisibility(View.GONE);
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		}
    }
}
